package com.itchen.repository.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchen.convert.UploadConvert;
import com.itchen.emtity.dataobject.UploadDO;
import com.itchen.emtity.po.UploadPO;
import com.itchen.exception.BusinessException;
import com.itchen.exception.code.BaseResponseCode;
import com.itchen.repository.FileUploadRepository;
import com.itchen.repository.impl.mapper.FileUploadMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class FileUploadRepositoryImpl implements FileUploadRepository {

    @Autowired
    private FileUploadMapper fileUploadMapper;

    @Autowired
    private UploadConvert uploadConvert;

    /**
     * 将上传文件后的数据保存到数据库
     * @param upload
     * @return
     */
    @Override
    public int createUploadData(UploadDO upload) {

        return fileUploadMapper.createUploadData(uploadConvert.uploadDOToPO(upload));
    }

    @Override
    public List<UploadDO> getUploadFileList(String orName) {
        List<UploadPO> uploadPOList =  fileUploadMapper.getUploadFileList(orName);
        return uploadPOList.parallelStream().map(uploadConvert::uploadPOToDO).collect(Collectors.toList());
    }

    @Override
    public void deleteUploadFileDataById(String uploadId) {
        int row = fileUploadMapper.deleteUploadFileDataById(uploadId);
        if (row == 0){
            throw new BusinessException(BaseResponseCode.DELETE_ERROR);
        }
    }

    @Override
    public int getCount() {
        return fileUploadMapper.getCount();
    }

    @Override
    public UploadDO getUploadFileById(String uploadId) {
        UploadPO uploadPO = fileUploadMapper.getUploadFileById(uploadId);
        if (uploadPO == null){
            throw new BusinessException(BaseResponseCode.ID_ERROR);
        }
        return uploadConvert.uploadPOToDO(uploadPO);
    }

    /**
     * 下载数量加一
     * @param uploadDO
     */
    @Override
    public void downloadNumberAddOne(UploadDO uploadDO) {
        fileUploadMapper.downloadNumberAddOne(uploadDO.getUploadId(),uploadDO.getDownloadNumber()+1);
    }

    @Override
    public void deleteUploadFileDataByIds(List<UploadDO> uploadDOS) {
        List<UploadPO> uploadPOS = uploadDOS.parallelStream().map(uploadConvert::uploadDOToPO).collect(Collectors.toList());
        int row = fileUploadMapper.deleteUploadFileDataByIds(uploadPOS);
        System.out.println("=====row:"+row);
        if (row == 0){
            throw new BusinessException(BaseResponseCode.DELETE_ERROR);
        }
    }

}
